package com.rjkj.medicalwaste.ui.storage

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.rjkj.medicalwaste.MainActivity
import com.rjkj.medicalwaste.R
import com.rjkj.medicalwaste.adapter.ItemClick
import com.rjkj.medicalwaste.adapter.OpenBoxAdapter
import com.rjkj.medicalwaste.base.checkState
import com.rjkj.medicalwaste.base.showTip
import com.rjkj.medicalwaste.bean.GarbageBean
import com.rjkj.medicalwaste.bean.GarbageStatus
import com.rjkj.medicalwaste.bean.MedicalWasteType
import com.rjkj.medicalwaste.bean.ReviewWeightState
import com.rjkj.medicalwaste.database.GarbageSetBoxed
import com.rjkj.medicalwaste.database.GarbageSetUnReview
import com.rjkj.medicalwaste.databinding.DialogOpenBoxBinding
import com.rjkj.medicalwaste.livedatabus.LiveDataBus
import com.rjkj.medicalwaste.utils.TimeUtils
import com.rjkj.medicalwaste.viewmodels.UnBoxedViewModel
import com.rjkj.medicalwaste.viewmodels.UserViewModel
import com.rjkj.medicalwaste.viewmodels.provider.MainViewModelProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.math.BigDecimal


class OpenBoxDialog : DialogFragment() {
    private var reviewWeightDialog: ReviewWeightForBoxDialog? = null
    private var unReviewWeightDialog: UnReviewWeightForBoxDialog? = null
    private val unBoxedViewModel: UnBoxedViewModel by viewModels {
        MainViewModelProvider.provideUnBoxedModel(requireContext())
    }
    private val userViewModel: UserViewModel by activityViewModels {
        MainViewModelProvider.provideUserModel(requireContext())
    }
    private val openBoxAdapter = OpenBoxAdapter(object : ItemClick<GarbageBean> {
        override fun onClicked(view: View, value: GarbageBean) {
            lifecycleScope.launch {
                val currentTime = TimeUtils.getYMDHMSTime()
                unBoxedViewModel.updateGarbageSetBoxed(
                    GarbageSetBoxed(
                        id = value.id,
                        garbageUserStatus = GarbageStatus.review,
                        garbageQRCode = value.garbageQRCode,
                    )
                )
                unBoxedViewModel.updateGarbageSetUnReview(
                    GarbageSetUnReview(
                        id = value.id,
                        garbageQRCode = value.garbageQRCode,
                        garbageUserStatus = GarbageStatus.loading,
                        reviewWeightState = ReviewWeightState.UnCheck
                    )
                )
                val finalBoxGarbageBean = unBoxedViewModel.repository.getBoxGarbageBean(
                    userViewModel.hospitalId.value
                        ?: "", value.garbageBoxQRCode
                )
                unBoxedViewModel.repository.updateChangeGarbageFromBox(
                    value.garbageBoxQRCode,
                    finalBoxGarbageBean.sumOf { BigDecimal(it.garbageWeight) }
                        .setScale(2, BigDecimal.ROUND_HALF_UP).toString(),
                    finalBoxGarbageBean.size,
                    currentTime
                )
                val current = unBoxedViewModel.repository.findGarbageByCode2(value.garbageQRCode)
                //先将删除的垃圾同步一次
                if(current!=null){
                    userViewModel.uploadGarbage(
                        garbageBeanList = listOf(current),
                        successState = GarbageBean.storeState,
                        failState = GarbageBean.nullState
                    )
                }

                //再将删除的垃圾所在箱子的垃圾影响的也同步
                val findList =
                    unBoxedViewModel.repository.findGarbageByBoxCode(value.garbageBoxQRCode)
                if (findList.isNotEmpty()) {
                    userViewModel.uploadGarbage(
                        garbageBeanList = findList,
                        successState = GarbageBean.storeState,
                        failState = GarbageBean.nullState
                    )
                }

            }

        }
    })


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        val binding = DialogOpenBoxBinding.inflate(inflater, container, false)
        binding.btCloseBox.setOnClickListener {
            dismiss()
        }
        binding.list.apply {
            val dividerItemDecoration =
                DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL)
            addItemDecoration(dividerItemDecoration)
            layoutManager = LinearLayoutManager(requireContext())
            openBoxAdapter.addLoadStateListener {
                when (it.refresh) {
                    is LoadState.Loading -> {
                        binding.load.visibility = View.VISIBLE
                    }
                    is LoadState.NotLoading -> {
                        binding.load.visibility = View.INVISIBLE
                    }
                    else -> binding.load.visibility = View.INVISIBLE
                }
            }
            adapter = openBoxAdapter
        }
        val boxCode = arguments?.getString(BoxListFragment.BOX_CODE)
        val boxType = arguments?.getString(BoxListFragment.BOX_TYPE)
        boxCode.let {
            if (it != null) {
                lifecycleScope.launchWhenResumed {
                    unBoxedViewModel.getOpenBoxGarbagePaging(it).collect { paging ->
                        openBoxAdapter.submitData(paging)
                    }
                }
            }
        }
        LiveDataBus.get().with(MainActivity.SCAN_DATA, String::class.java).observe(
            viewLifecycleOwner, {
                Log.e("addBox", "onCreateView: $it", )
                if (it.length >= 74 || it.length == 49) {
                    val code = if(it.length==49){"1" + it.split("?").last()}else{it.split("?").last()}
                    lifecycleScope.launch {
                        val findGarbageByCodeAndStatus =
                            unBoxedViewModel.repository.findGarbageByCode2(code)
                        if (findGarbageByCodeAndStatus != null) {
                            if (findGarbageByCodeAndStatus.reviewStorageQRCode != userViewModel.stagingRoomUser.value?.qrcode ?: "") {
                                showTip("医废不属于该暂存间")
                                return@launch
                            }
                            val garbageType =
                                MedicalWasteType.getBoxTypeByTypeName(findGarbageByCodeAndStatus.garbageType)
                            val boxGarbageType =
                                MedicalWasteType.getBoxTypeByTypeName(boxType ?: "")
                            if (garbageType != boxGarbageType) {
                                showTip("请扫入${boxGarbageType.typeConfig}类型医废")
                                return@launch
                            }
                            if (findGarbageByCodeAndStatus.garbageUserStatus == GarbageStatus.loading) {
                                if (userViewModel.setting.value?.review == true) {//复核模式
                                    if (reviewWeightDialog != null && reviewWeightDialog!!.showsDialog) {
                                        parentFragmentManager.findFragmentByTag("ReviewWeightForBoxDialog")
                                            ?.let { dialog ->
                                                (dialog as DialogFragment).dismiss()
                                            }
                                    }
                                    reviewWeightDialog = ReviewWeightForBoxDialog().apply {
                                        val bundle = Bundle()
                                        bundle.putString(BoxListFragment.BOX_CODE, boxCode)
                                        bundle.putString(BoxListFragment.BOX_TYPE,boxType)
                                        bundle.putString(BoxListFragment.GARBAGE_TYPE, code)
                                        this.arguments = bundle
                                        setStyle(STYLE_NORMAL, R.style.dialogNormal)//添加上面创建的style
                                    }
                                    reviewWeightDialog!!.show(
                                        parentFragmentManager,
                                        "ReviewWeightForBoxDialog"
                                    )

                                } else {//不复核模式
                                    if (unReviewWeightDialog != null && unReviewWeightDialog!!.showsDialog) {
                                        parentFragmentManager.findFragmentByTag("UnReviewWeightForBoxDialog")
                                            ?.let { dialog ->
                                                (dialog as DialogFragment).dismiss()
                                            }
                                    }
                                    unReviewWeightDialog = UnReviewWeightForBoxDialog().apply {
                                        val bundle = Bundle()
                                        bundle.putString(BoxListFragment.BOX_CODE, boxCode)
                                        bundle.putString(BoxListFragment.BOX_TYPE,boxType)
                                        bundle.putString(BoxListFragment.GARBAGE_TYPE, code)
                                        this.arguments = bundle
                                        setStyle(STYLE_NORMAL, R.style.dialogNormal)//添加上面创建的style
                                    }
                                    unReviewWeightDialog!!.show(
                                        parentFragmentManager,
                                        "UnReviewWeightForBoxDialog"
                                    )
                                }
                            } else {
                                showTip("无法添加${checkState(findGarbageByCodeAndStatus.garbageUserStatus)}医废")
                            }
                        } else {
                            showTip("未找到有效医废信息")
                        }

                    }

                } else {
                    showTip("请扫描医废二维码")
                }

            })
        binding.lifecycleOwner = viewLifecycleOwner
        return binding.root

    }

    override fun onStart() {
        dialog!!.window!!.apply {
            attributes.width = ViewGroup.LayoutParams.MATCH_PARENT //宽度铺满
            attributes.height = ViewGroup.LayoutParams.MATCH_PARENT
            attributes.gravity = Gravity.BOTTOM//位于底部
            decorView.background = ColorDrawable(Color.TRANSPARENT)//背景色
        }
        super.onStart()
    }
//    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
//        return activity?.let {
//            // Use the Builder class for convenient dialog construction
//            val builder = AlertDialog.Builder(it)
//            builder.setMessage("a")
//                    .setPositiveButton("b",
//                            DialogInterface.OnClickListener { dialog, id ->
//                                // FIRE ZE MISSILES!
//                            })
//                    .setNegativeButton("c",
//                            DialogInterface.OnClickListener { dialog, id ->
//                                // User cancelled the dialog
//                            })
//            // Create the AlertDialog object and return it
//            builder.create()
//        } ?: throw IllegalStateException("Activity cannot be null")
//    }
}